﻿using Sidvall.Serialization;
using System;
using System.Globalization;
using System.Windows.Data;

namespace Sidvall.UI.Wpf.Converters
{
    public abstract class ValueToStringConverterBase : IValueConverter
    {
        #region Public Members

        protected abstract object StringToValue(object value, Type targetType, object parameter, CultureInfo culture);

        #region Inverted

        private bool _Inverted = false;
        public bool Inverted
        {
            get
            {
                return _Inverted;
            }
            set
            {
                _Inverted = value;
            }
        }

        #endregion

        #region Convert

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (!this.Inverted)
                return ValueToString(value, targetType, parameter, culture);
            else
                return StringToValue(value, targetType, parameter, culture);
        }

        #endregion
        #region ConvertBack

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (!this.Inverted)
                return StringToValue(value, targetType, parameter, culture);
            else
                return ValueToString(value, targetType, parameter, culture);
        }

        #endregion

        #region ValueToString

        protected virtual string ValueToString(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var format = parameter.ToString(null);
            if (!string.IsNullOrWhiteSpace(format))
                return string.Format(culture, format, value);
            return value.ToString(null);
        }

        #endregion

        #endregion
    }
}
